package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Personal;
import cn.wolfcode.wolf2w.query.PersonalQuery;
import cn.wolfcode.wolf2w.repository.PersonalRepository;
import cn.wolfcode.wolf2w.service.IPersonalService;
import cn.wolfcode.wolf2w.service.IPersonalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class PersonalServiceImpl implements IPersonalService {


    //在这里引用后期后台项目引用会导致报错
   /* @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.Key")
    private String appKey;*/


    @Autowired
    private PersonalRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Personal personal) {
        repository.save(personal);
    }


    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Personal get(String id) {
        Personal personal = repository.findById(id).get();
        return personal;
    }

    @Override
    public List<Personal> list() {
        List<Personal> personals = repository.findAll();
        return personals;
    }

    //分页查询
    @Override
    public Page<Personal> query(PersonalQuery qo) {
        Query query = new Query();
        //repository只能针对所有数据进行分页
        //template不能直接对数据进行分页
        //使用template间接分页
        //pageResult 核心字段
        //totalCount 总记录数
        long totalcount = template.count(query, Personal.class);
        if (totalcount == 0) {
            //空的分页对象
            return Page.empty();
        }
        //list 当前页显示数据集合
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Personal> list = template.find(query, Personal.class);
        return new PageImpl<>(list, pageable, totalcount);
    }

    @Override
    public Personal getByUserId(String userId) {
        Personal personal=repository.findByUserId(userId);
        return personal;
}


}
